import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { DiscardedIotSimTableListItem, MultiSimOperInfo } from '../typings.d';
import { getFlowPercent } from '../utils';
import { Progress, Table, Tooltip } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  deleteDiscardIotSim,
  deleteMultiDiscardIotSim,
  queryDiscardedIotSimList,
} from '../service';
import { useModel } from 'umi';
import { Auths } from '@/utils/typings.d';
import ConfirmModal from '@/components/ConfirmModal';
import { useRef } from 'react';

const DiscardedIotSimList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.iotSim || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<DiscardedIotSimTableListItem>[] = [
    {
      title: 'key',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '流量卡号',
      width: 300,
      hideInForm: true,
      dataIndex: 'iccid',
      align: 'center',
    },
    {
      title: '舍弃时间',
      dataIndex: 'discardTime',
      align: 'center',
      // hideInSearch: true,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '舍弃人员',
      dataIndex: 'discardOper',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => record.discardOperName || record.discardOper,
    },
    {
      title: '设备类型',
      width: 120,
      dataIndex: 'deviceType',
      align: 'center',
      valueEnum: {
        0: { text: '视频巡检车' },
        1: { text: 'GPS设备' },
        2: { text: '4G车位锁' },
        3: { text: '4G流量主机' },
        4: { text: '诱导屏控制卡' },
        99: { text: '其他设备' },
      },
    },
    {
      title: '供应商',
      dataIndex: 'provider',
      align: 'center',
      valueEnum: {
        tibiot: { text: '齐犇' },
        upiot: { text: '量讯' },
        dahan: { text: '大汉三通' },
      },
    },
    {
      title: '运营商',
      dataIndex: 'supplier',
      align: 'center',
      valueEnum: {
        CMCC: { text: '中国移动' },
        CTCC: { text: '中国电信' },
        CUCC: { text: '中国联通' },
      },
    },
    {
      title: '套餐名称',
      dataIndex: 'pkgName',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '流量大小',
      hideInSearch: true,
      dataIndex: 'totalFlow',
      align: 'center',
    },
    {
      title: '已用流量',
      hideInSearch: true,
      dataIndex: 'usedFlow',
      align: 'center',
    },
    {
      title: '剩余流量',
      hideInSearch: true,
      hideInForm: true,
      dataIndex: 'usedFlow',
      align: 'center',
      render: (_, record) => {
        const per = getFlowPercent(record.usedFlow, record.totalFlow);
        const preRemain = 100 - Number(per) >= 0 ? 100 - Number(per) : 0;
        const remain = Number(preRemain.toFixed(2));
        if (remain > 10) {
          return (
            <Tooltip title={`${remain}%`}>
              <Progress
                style={{ minWidth: '110px', maxWidth: '200px' }}
                success={{ percent: remain }}
                showInfo={false}
                percent={remain}
                size="small"
              />
            </Tooltip>
          );
        } else {
          return (
            <Tooltip title={`${remain}%`}>
              <Progress
                status="exception"
                style={{ minWidth: '110px', maxWidth: '200px' }}
                showInfo={false}
                percent={remain}
                size="small"
              />
            </Tooltip>
          );
        }
      },
    },
    {
      title: '添加时间',
      dataIndex: 'addTime',
      align: 'center',
      hideInSearch: true,
      valueType: 'date',
    },
    {
      title: '激活时间',
      dataIndex: 'activeTime',
      align: 'center',
      hideInSearch: true,
      valueType: 'date',
    },
    {
      title: '过期时间',
      dataIndex: 'pkgExpiredTime',
      align: 'center',
      // hideInSearch: true,
      valueType: 'date',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'application',
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      hideInTable: !ifDelete,
      render: (_, record, x, action) => (
        <ConfirmModal
          key={`${record._id}_delete`}
          reload={() => action?.reload()}
          operFunc={async () => await deleteDiscardIotSim(record._id)}
        />
      ),
    },
  ];

  return (
    <PageHeaderWrapper
      title={false}
      content="流量卡过期三天之后系统会自动迁移到此表，此表不再进行过期通知"
    >
      <ProTable<DiscardedIotSimTableListItem>
        columns={columns}
        rowKey={'_id'}
        scroll={{ x: true }}
        actionRef={actionRef}
        style={{ whiteSpace: 'nowrap' }}
        search={{ labelWidth: 'auto' }}
        request={queryDiscardedIotSimList}
        dateFormatter="string"
        pagination={{
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        rowSelection={
          ifDelete && {
            selections: [Table.SELECTION_ALL],
          }
        }
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        )}
        tableAlertOptionRender={({ selectedRows, onCleanSelected }) => {
          const operInfo: MultiSimOperInfo[] =
            selectedRows?.map((item) => {
              return {
                id: item._id,
                iccid: item.iccid,
                ownerId: item.ownerId,
                provider: item.provider,
              };
            }) || [];
          return (
            <ConfirmModal
              key={'muliti_delete'}
              btnText="批量删除"
              reload={() => {
                onCleanSelected();
                actionRef.current?.reload();
              }}
              text={'确定要删除这些流量卡吗？'}
              operFunc={async () => await deleteMultiDiscardIotSim({ sims: operInfo })}
            />
          );
        }}
      />
    </PageHeaderWrapper>
  );
};

export default DiscardedIotSimList;
